#!/usr/bin/env python3
import csv
from shutil import get_terminal_size

in_csv = '/home/ubantu00/zk_demo/build/results_summary.csv'
out_txt = '/home/ubantu00/zk_demo/build/results_summary_pretty.txt'

rows = []
with open(in_csv, newline='') as f:
    reader = csv.reader(f)
    for r in reader:
        rows.append(r)

if not rows:
    print('no rows')
    raise SystemExit(1)

header = rows[0]
data = rows[1:]
# compute column widths
col_widths = [len(h) for h in header]
for r in data:
    for i, cell in enumerate(r):
        col_widths[i] = max(col_widths[i], len(str(cell)))

# cap total width to terminal width for readability
term_w = get_terminal_size((120, 20)).columns
# build format string
fmt_parts = []
for w in col_widths:
    fmt_parts.append('{:<%d}' % (w+2))
fmt = ''.join(fmt_parts)

with open(out_txt, 'w') as f:
    f.write(fmt.format(*header).rstrip() + '\n')
    f.write('-' * min(sum(col_widths) + 3 * len(col_widths), term_w) + '\n')
    for r in data:
        # ensure row length matches header
        r2 = [str(c) for c in r]
        if len(r2) < len(header):
            r2 += [''] * (len(header) - len(r2))
        f.write(fmt.format(*r2).rstrip() + '\n')

print('Wrote', out_txt)
